package com.ys.util.codegenerate.sqlserver;

import com.alibaba.fastjson.JSON;
import freemarker.template.Template;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class CodeGenerateSqlServerUtilfxz {
	
	@SuppressWarnings("serial")
	private static Map<String, String> JDBC_JAVA_COL_MAP = new HashMap<String, String>(){{
		put("varchar", "String");
		put("nvarchar", "String");
		put("text", "String");
		put("date", "String");
		put("int", "Integer");
		put("tinyint", "Integer");
		put("bigint", "Long");
		put("decimal", "BigDecimal");
		put("bit", "Integer");
		put("datetime", "Date");
		put("char", "String");
	}};

	// 项目的通用路径D:\ideaWorkSpace\miniease
	private static String projectCodeArr[] = {
			"D:/workspace_ys/miniease/miniease_common", // XDH
			"D:/miniease/miniease_common",	// FXZ
			"D:/ideaWorkSpace/miniease/miniease_common"	,// LZM
			"D:/javawork/miniease/miniease_common",	// XJX
			};

	/*
	 * TODO 生成时，每次都要修改
	 */
	private static String PACKAGE = "storage"; // TODO 包名
	private static String DATABASE_NAME = "kjecp"; // TODO 数据库名
	private static String NAME_TABLE = "TCC_FbaDeliverItem"; // TODO 表名
	private static String NAME_CLASS_PRE = "TccFbaDeliverItem"; // TODO 类名前缀




	// entity所在的包名
	private static String PACKAGE_ENTITY = "com.ys.entity." + PACKAGE;
	// mapper所在的包名
	private static String PACKAGE_MAPPER = "com.ys.mapper." + PACKAGE;

	private static String JDBC_URL = "jdbc:sqlserver://192.168.30.19:1433;databaseName=" + DATABASE_NAME + ";integratedSecurity=false;";
	private static String USERNAME = "sa";
	private static String PASSWORD = "123456";


	public static void main(String[] args) {
		try {
			generateEntity();
			generateMapperjava();
			generateMapperxml();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static List<Column> getListColumn() {
		List<Column> listColumn = new ArrayList<Column>();
		try {
			Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}

		try {
			Connection con = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
			Statement stmt = con.createStatement();
			String SQL = "SELECT s1.name AS nameCol,s3.name AS nameType FROM syscolumns s1"
					+ " left join sysobjects s2 on s1.id=s2.id"
					+ " left join systypes s3 on s1.xtype=s3.xtype"
					+ " where s2.name = '" + NAME_TABLE + "' and s3.name != 'sysname' order by s1.colorder asc";

			ResultSet rs = stmt.executeQuery(SQL);

			while (rs.next()) {
				String nameCol = rs.getString("nameCol");
				String nameType = JDBC_JAVA_COL_MAP.get(rs.getString("nameType"));
				System.out.println(rs.getString("nameCol") + "---" + rs.getString("nameType"));
				listColumn.add(new Column(nameCol, nameType, rs.getString("nameType")));
			}

		} catch (SQLException e) {

			e.printStackTrace();

		}
		
		return listColumn;
	}
	
	private static Table getTable() {
		String nameClass = NAME_CLASS_PRE;
		List<Column> listColumn = getListColumn();

		String nameTable = NAME_TABLE;
		String nameTableWithDbo = DATABASE_NAME.equals("kjecp") ? NAME_TABLE : "[" + DATABASE_NAME + "].[dbo]." + NAME_TABLE;
		boolean hasDecimal = false;
		boolean hasDate = false;
		String primaryKey = "Guid";
		for(Column column: listColumn) {
			if ("BigDecimal".equals(column.getNameType())) {
				hasDecimal = true;
			} else if ("Date".equals(column.getNameType())) {
				hasDate = true;
			}
			
			if (column.getNameCol().equals("Id")) {
				primaryKey = "Id";
			}
		}
		return new Table(nameClass, nameTable, nameTableWithDbo, listColumn, hasDecimal, hasDate, primaryKey);
	}

	private static void generateEntity() throws Exception {
		
		// 判断路径是否存在
		for (String str : projectCodeArr) {
			String pathDir = str + "/src/main/java" + "/" + PACKAGE_ENTITY.replace(".", "/") + "/";
			File fileDir = new File(pathDir);
			if (!fileDir.exists()) {
				System.out.println("不存在---" + fileDir.getPath());
			} else {
				// 文件路径
				String pathFile = pathDir + NAME_CLASS_PRE + ".java";
				System.out.println(pathFile);
				File file = new File(pathFile);
				
				Table table = getTable();
				System.out.println(JSON.toJSONString(table));
				Map<String, Object> dataMap = new HashMap<>();
				dataMap.put("table", table);
				dataMap.put("packageEntity", PACKAGE_ENTITY);
				
				String templateName = "Entity.ftl";
				
				generateFileByTemplate(templateName, file, dataMap);
			}
		}
	}

	private static void generateMapperjava() throws Exception {
		
		// 判断路径是否存在
		for (String str : projectCodeArr) {
			
			File dir = new File(str);
			if (!dir.exists()) {
				System.out.println("不存在---" + dir.getPath());
				continue;
			} else {
				System.out.println("存在---" + dir.getPath());
			}
			
			// 文件路径
			String pathFile = str + "/src/main/java" + "/" + PACKAGE_MAPPER.replace(".", "/") + "/" + NAME_CLASS_PRE + "Mapper.java";
			
			System.out.println(pathFile);
			File file = new File(pathFile);
			
			Table table = getTable();
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("table", table);
			dataMap.put("packageMapper", PACKAGE_MAPPER);
			dataMap.put("packageEntity", PACKAGE_ENTITY);
			
			String templateName = "Mapperjava.ftl";
			
			generateFileByTemplate(templateName, file, dataMap);
		}
	}

	private static void generateMapperxml() throws Exception {
		
		// 判断路径是否存在
		for (String str : projectCodeArr) {
			
			File dir = new File(str);
			if (!dir.exists()) {
				System.out.println("不存在---" + dir.getPath());
				continue;
			} else {
				System.out.println("存在---" + dir.getPath());
			}
			
			// 文件路径
			String pathFile = str + "/src/main/resources/mapper/" + PACKAGE + "/" + NAME_CLASS_PRE + "Mapper.xml";
			System.out.println(pathFile);
			File file = new File(pathFile);
			
			Table table = getTable();
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("table", table);
			dataMap.put("packageMapper", PACKAGE_MAPPER);
			dataMap.put("packageEntity", PACKAGE_ENTITY);
			
			String templateName = "Mapperxml.ftl";
			
			generateFileByTemplate(templateName, file, dataMap);
		}
	}

	private static void generateFileByTemplate(String templateName, File file, Map<String, Object> dataMap)
			throws Exception {
		
//		if (file.exists()) {
//			System.out.println("已存在---" + file.getPath());
//			return;
//		}
		
		Template template = FreeMarkerTemplateUtil.getTemplate(templateName);
		FileOutputStream fos = new FileOutputStream(file);
		Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
		template.process(dataMap, out);
	}

}